package com.qf.openapi.web.master.utils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class FileAppender {
    private String filename;

    private BufferedWriter bufferedWriter;

    public FileAppender(String filename) throws IOException {
        this.filename = filename;
        // 输出流
        this.bufferedWriter = new BufferedWriter(new FileWriter(filename,true));
    }


    public Integer append(List<String> data) throws IOException {
        AtomicInteger count = new AtomicInteger();
        // 遍历list，将其中的String写入到文本文件中
        data.forEach(s -> {
            try {
                bufferedWriter.write(s);
                bufferedWriter.newLine(); // 增加换行
                count.getAndIncrement();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        bufferedWriter.flush(); // 刷新缓冲区的数据
//        bufferedWriter.close(); // 不能在这里关闭
        return count.get();
    }

    /**
     * 关闭打开的流对象
     */
    public void close() throws IOException {
        bufferedWriter.close();
    }

    public static void main(String[] args) throws IOException {
        final FileAppender fileAppender = new FileAppender("data.txt");
        final Integer append = fileAppender.append(Arrays.asList("aaaaaaa", "bbbbbb", "ccccc"));
        final Integer append1 = fileAppender.append(Arrays.asList("aaaaaaa", "bbbbbb", "ccccc"));

        System.out.println(append);
        System.out.println(append1);
        fileAppender.close(); // 关闭资源
    }
}
